package cn.edu.pzhu.javaweb.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.pzhu.javaweb.pojo.Result;
import cn.edu.pzhu.javaweb.service.UserService;
import cn.edu.pzhu.javaweb.service.imp.UserServiceImp;

/**
 * Servlet implementation class DestroyAccountServlet
 */
@WebServlet("/destroy")
public class DestroyAccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private UserService userService = new UserServiceImp();
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DestroyAccountServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		
		// 获取当前登录用户名
		HttpSession session = request.getSession();
		String username = (String) session.getAttribute("username");
		
		if (username == null) {
		    response.getWriter().print("<script>alert('请先登录!');location.href='login.jsp';</script>");
		    return;
		}
		
		// 执行账户注销
		Result<String> result = userService.destroyAccount(username);
		
		if (result.getCode() == 200) {
		    // 注销成功，使session失效并跳转到登录页面
		    session.invalidate();
		    response.getWriter().print("<script>alert('账户注销成功!');location.href='login.jsp';</script>");
		} else {
		    // 注销失败
		    response.getWriter().print("<script>alert('账户注销失败: " + result.getMessage() + "');location.href='index.jsp';</script>");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}